package com.example.geoaimavlink_android.widget;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.geoaimavlink_android.R;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class MediaView extends AppCompatActivity implements View.OnClickListener {

    private final static String MEDIA_SERVER_URL = "10.134.79.200";

    private final static String MEDIA_SERVER_PORT = "8000";

    private final static String MEDIA_SERVER_DO_NAME_PATH = "/xzj";

    private final static String MEDIA_SERVER_PATH = "http://" + MEDIA_SERVER_URL + ":" + MEDIA_SERVER_PORT + MEDIA_SERVER_DO_NAME_PATH;

    private final static String MEDIA_SERVER_MEDIA_LIST = MEDIA_SERVER_PATH + "?json=true";

    private RecyclerView mRcyMedia;

    private MediaFile mMediaFile;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_media);
        findViewById(R.id.btn_obtain_media_list).setOnClickListener(this);
        findViewById(R.id.btn_show_media_list).setOnClickListener(this);
        mRcyMedia = findViewById(R.id.rcy_media);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_obtain_media_list) {
            new Thread(this::getMediaList).start();
        } else if (v.getId() == R.id.btn_show_media_list) {
            RecycleAdapter adapter = new RecycleAdapter(this, mMediaFile);
            mRcyMedia.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
            mRcyMedia.setAdapter(adapter);
        }
    }

    private void getMediaList() {
        try {
            URL url = new URL(MEDIA_SERVER_MEDIA_LIST);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                showToast("connect error: " + responseCode);
                return;
            }
            StringBuilder result = new StringBuilder();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            Log.i("Ronny", result.toString());
            mMediaFile = new Gson().fromJson(result.toString(), MediaFile.class);
            int fileSize = mMediaFile.getFiles().size();
            showToast("file size: " + fileSize);
            setShowMediaEnable(fileSize > 0);
        } catch (Exception e) {
            showToast("unknown exception: " + Log.getStackTraceString(e));
            e.printStackTrace();
        }
    }

    private void setShowMediaEnable(boolean isEnable) {
        runOnUiThread(() -> findViewById(R.id.btn_show_media_list).setEnabled(isEnable));
    }

    private void showToast(String msg) {
        runOnUiThread(() -> Toast.makeText(this, msg, Toast.LENGTH_SHORT).show());
    }

    public static class MediaFile {

        private List<Files> files;

        public List<Files> getFiles() {
            return files;
        }

        public void setFiles(List<Files> files) {
            this.files = files;
        }

        public static class Files {
            private String name;
            private String path;
            private String type;
            private Integer size;
            private Long mtime;

            public String getName() {
                return name;
            }

            public void setName(String name) {
                this.name = name;
            }

            public String getPath() {
                return path;
            }

            public void setPath(String path) {
                this.path = path;
            }

            public String getType() {
                return type;
            }

            public void setType(String type) {
                this.type = type;
            }

            public Integer getSize() {
                return size;
            }

            public void setSize(Integer size) {
                this.size = size;
            }

            public Long getMtime() {
                return mtime;
            }

            public void setMtime(Long mtime) {
                this.mtime = mtime;
            }
        }
    }

    public static class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.VH>{

        private Context context;

        private MediaFile mediaFile;

        public RecycleAdapter(Context context, MediaFile mediaFile) {
            this.context = context;
            this.mediaFile = mediaFile;
        }

        @NonNull
        @Override
        public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(context).inflate(R.layout.item_media_recycle, parent, false);
            return new VH(view);
        }

        @Override
        public void onBindViewHolder(@NonNull VH holder, int position) {
            holder.mTv.setText(mediaFile.getFiles().get(position).getPath());
            String name = mediaFile.getFiles().get(position).getName();
            Glide.with(context).load(MEDIA_SERVER_PATH + File.separator + name).into(holder.mImg);
        }

        @Override
        public int getItemCount() {
            return mediaFile.getFiles().size();
        }

        private static class VH extends RecyclerView.ViewHolder {

            private final TextView mTv;

            private final ImageView mImg;

            public VH(@NonNull View itemView) {
                super(itemView);
                mTv = itemView.findViewById(R.id.item_text);
                mImg = itemView.findViewById(R.id.item_image);
            }
        }
    }
}
